<template>
  <div class="mod-config">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <el-form-item>
        <el-input v-model="dataForm.key" size="mini" placeholder="参数名" clearable @clear="getDataList()"
          @blur="getDataList()"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="mini" type="success" @click="getDataList()" icon="el-icon-search">查询</el-button>
        <el-button @click="resetForm" size="mini" type="warning" icon="el-icon-refresh-left">重置</el-button>
      </el-form-item>
    </el-form>
    <el-form>
      <el-form-item>
        <el-button-group>
          <el-button size="mini" v-if="isAuth('product:supplier:save')" type="primary"
            @click="addOrUpdateHandle()" icon="el-icon-plus">新增</el-button>
          <el-button size="mini" v-if="isAuth('product:supplier:delete')" type="danger" @click="deleteHandle()"
            icon="el-icon-delete" :disabled="dataListSelections.length <= 0">删除</el-button>
        </el-button-group>
        <el-button-group>
          <el-button size="mini" v-if="isAuth('product:supplier:export')" type="info" @click="exportData"
            class="iconfont icon-topsales">导出</el-button>
          <el-button size="mini" v-if="isAuth('product:supplier:import')" type="info" @click="importData()"
            class="iconfont icon-skip">导入</el-button>
        </el-button-group>
      </el-form-item>
      <el-form-item>
        <el-dialog title="导入数据" :visible.sync="upload.open" width="400px" append-to-body :close-on-click-modal="false">
          <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
            :before-upload="beforeUpload" :action="upload.url" :disabled="upload.isUploading"
            :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false"
            :file-list="excelList" :on-remove="onRemoveDr" :on-change="onChangeDr" drag>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或
              <em>点击上传</em>
            </div>
            <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
          </el-upload>
          <el-button size="mini" type="success" @click="downloadImportTemplate">下载模板</el-button>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitFileForm">导 入</el-button>
            <el-button @click="cancelFileForm">取 消</el-button>
          </div>
        </el-dialog>
      </el-form-item>
    </el-form>
    <el-table :data="dataList" size="mini" v-loading="dataListLoading" @selection-change="selectionChangeHandle"
      style="width: 100%;" @cell-click="tableDbEdit" @cell-dblclick="tableDbEdit"
      :header-cell-style="{ background: '#fcfcfc', color: '#606266', height:'36px'}">
      <el-table-column type="selection" header-align="center" align="center" width="50">
      </el-table-column>
      <el-table-column prop="supllierType" header-align="center" align="center" label="供应商类型" width="150">
        <template slot-scope="scope">
          <!-- <el-input size="mini" v-model="scope.row.supllierType" v-if="showInput == `supllierType${scope.row.supplierId}`"
            @blur='blurInput(scope.row, "supllierType", scope.row.supllierType)' v-focus>
          </el-input> -->
          <el-select v-model="scope.row.supllierType" v-if="showInput == `supllierType${scope.row.supplierId}`" size="mini"
           @change='blurInput(scope.row, "supllierType", scope.row.supllierType)' v-focus clearable placeholder="请选择"
            @focus="getDicts('SUPPLY_TYPE')">
            <el-option v-for="(item,index) in supllierTypes" :key="item.value" :label="item.label" :value="item.label">
            </el-option>
           </el-select>
          <span v-else style="text-decoration:none;">{{scope.row.supllierType}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="supplierName" header-align="center" align="center" label="供应商名称" width="160" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-input size="mini" v-model="scope.row.supplierName" v-if="showInput == `supplierName${scope.row.supplierId}`"
            @blur='blurInput(scope.row, "supplierName", scope.row.supplierName)' v-focus>
          </el-input>
          <span v-else style="text-decoration:none;">{{scope.row.supplierName}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" header-align="center" align="center" label="状态">
        <template slot-scope="scope">
          <el-switch size="mini" v-model="scope.row.status" @change="saveHandle(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="address" header-align="center" align="center" label="地址" width="180" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-input size="mini" v-model="scope.row.address" v-if="showInput == `address${scope.row.supplierId}`"
            @blur='blurInput(scope.row, "address", scope.row.address)' v-focus>
          </el-input>
          <span v-else style="text-decoration:none;">{{scope.row.address}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="salesman" header-align="center" align="center" label="销售人员">
        <template slot-scope="scope">
          <el-input size="mini" v-model="scope.row.salesman" v-if="showInput == `salesman${scope.row.supplierId}`"
            @blur='blurInput(scope.row, "salesman", scope.row.salesman)' v-focus>
          </el-input>
          <span v-else style="text-decoration:none;">{{scope.row.salesman}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="tel" header-align="center" align="center" label="电话" width="120" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-input size="mini" v-model="scope.row.tel" v-if="showInput == `tel${scope.row.supplierId}`"
            @blur='blurInput(scope.row, "tel", scope.row.tel)' v-focus>
          </el-input>
          <span v-else style="text-decoration:none;">{{scope.row.tel}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="mobile" header-align="center" align="center" label="手机" width="120" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-input size="mini" v-model="scope.row.mobile" v-if="showInput == `mobile${scope.row.supplierId}`"
            @blur='blurInput(scope.row, "mobile", scope.row.mobile)' v-focus>
          </el-input>
          <span v-else style="text-decoration:none;">{{scope.row.mobile}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="corporater" header-align="center" align="center" label="法人代表">
        <template slot-scope="scope">
          <el-input size="mini" v-model="scope.row.corporater" v-if="showInput == `corporater${scope.row.supplierId}`"
            @blur='blurInput(scope.row, "corporater", scope.row.corporater)' v-focus>
          </el-input>
          <span v-else style="text-decoration:none;">{{scope.row.corporater}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="businessLicense" header-align="center" align="center" label="营业执照" width="160">
        <template slot-scope="scope">
          <el-image  v-for="(item,i) in scope.row.licensePics" class="col-image" @click="handleImgPreview(item.url,i)" :key="i" :src="item.url"  ></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="businessTimeLimit" header-align="center" align="center" label="营业执照期限" width="120">
        <template slot-scope="scope">
          <el-date-picker
            v-model="scope.row.businessTimeLimit"
            type="date"
            v-if="showInput == `businessTimeLimit${scope.row.supplierId}`"
            @blur='blurInput(scope.row, "businessTimeLimit", scope.row.businessTimeLimit)'
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
            v-focus>
          </el-date-picker>
          <span v-else style="text-decoration:none;">{{scope.row.businessTimeLimit}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="productBusinessLlicense" header-align="center" align="center" label="经营许可证" width="120">
        <template slot-scope="scope">
          <el-image  v-for="(item,i) in scope.row.businessPics" class="col-image" @click="handleImgPreview(item.url,i)" :key="i" :src="item.url"  ></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="productTimeLimit" header-align="center" align="center" label="许可证期限" width="120" >
        <template slot-scope="scope">
          <el-date-picker
            v-model="scope.row.businessTimeLimit"
            type="date"
            v-if="showInput == `productTimeLimit${scope.row.supplierId}`"
            @blur='blurInput(scope.row, "productTimeLimit", scope.row.productTimeLimit)'
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
            v-focus>
          </el-date-picker>
          <span v-else style="text-decoration:none;">{{scope.row.productTimeLimit}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="leader" header-align="center" align="center" label="负责人">
        <template slot-scope="scope">
          <el-input size="mini" v-model="scope.row.leader" v-if="showInput == `leader${scope.row.supplierId}`"
            @blur='blurInput(scope.row, "leader", scope.row.leader)' v-focus>
          </el-input>
          <span v-else style="text-decoration:none;">{{scope.row.leader}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="organizationCode" header-align="center" align="center" label="机构代码">
        <template slot-scope="scope">
          <el-input size="mini" v-model="scope.row.organizationCode"
            v-if="showInput == `organizationCode${scope.row.supplierId}`"
            @blur='blurInput(scope.row, "organizationCode", scope.row.organizationCode)' v-focus>
          </el-input>
          <span v-else style="text-decoration:none;">{{scope.row.organizationCode}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="organizationTimeLimit" header-align="center" align="center" label="机构期限" width="120">
        <template slot-scope="scope">
          <el-input size="mini" v-model="scope.row.organizationTimeLimit"
            v-if="showInput == `organizationTimeLimit${scope.row.supplierId}`"
            @blur='blurInput(scope.row, "organizationTimeLimit", scope.row.organizationTimeLimit)' v-focus>
          </el-input>
          <span v-else style="text-decoration:none;">{{scope.row.organizationTimeLimit}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="taxNumber" header-align="center" align="center" label="税务号">
        <template slot-scope="scope">
          <el-input size="mini" v-model="scope.row.taxNumber" v-if="showInput == `taxNumber${scope.row.supplierId}`"
            @blur='blurInput(scope.row, "taxNumber", scope.row.taxNumber)' v-focus>
          </el-input>
          <span v-else style="text-decoration:none;">{{scope.row.taxNumber}}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="dataDownloadCode" header-align="center" align="center" label="下载标识">
        <template slot-scope="scope">
          <el-input size="mini" v-model="scope.row.dataDownloadCode"
            v-if="showInput == `dataDownloadCode${scope.row.supplierId}`"
            @blur='blurInput(scope.row, "dataDownloadCode", scope.row.dataDownloadCode)' v-focus>
          </el-input>
          <span v-else style="text-decoration:none;">{{scope.row.dataDownloadCode}}</span>
        </template>
      </el-table-column> -->
      <el-table-column prop="isShare" header-align="center" align="center" label="门店共享">
        <template slot-scope="scope">
          <el-switch size="mini" v-model="scope.row.isShare" @change="saveHandle(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="storeName" header-align="center" align="center" label="门店名称" v-if="hasRole('role:sys:super:admin')">
      </el-table-column>
      <el-table-column prop="storeCode" header-align="center" align="center" label="门店编码"  v-if="hasRole('role:sys:super:admin')">
      </el-table-column>
      <el-table-column prop="updateTime" header-align="center" align="center" label="修改时间" width="140" >
      </el-table-column>
      <el-table-column prop="updateUsername" header-align="center" align="center" label="修改人">
      </el-table-column>
      <!-- <el-table-column prop="remark" header-align="center" align="center" label="备注">
        <template slot-scope="scope">
          <span v-html="scope.row.remark"></span>
        </template>
      </el-table-column> -->
      <el-table-column fixed="right" header-align="center" align="center" width="150" label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="text" v-if="isAuth('product:supplier:save')"
            @click="saveHandle(scope.row)">保存</el-button>
          <el-button size="mini" type="text" v-if="isAuth('product:supplier:update')"
            @click="addOrUpdateHandle(scope.row.supplierId)">修改</el-button>
          <el-button size="mini" type="text" v-if="isAuth('product:supplier:delete')"
            @click="deleteHandle(scope.row.supplierId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
    <!-- 图片预览对话框 -->
    <el-dialog v-drag title="图片预览" :visible.sync="imgDialogVisible" width="50%">
      <el-image style="width: 100%;" @close="handCloseImgDialog" :src="previewPath" ></el-image>
    </el-dialog>

  </div>
</template>

<script>
  import AddOrUpdate from './productsupplier-add-or-update'
  import {downLoadFile, dateFormat, hasRole} from '@/utils/myUtil.js'
  import {Loading} from "element-ui"

  export default {
    data() {
      return {
        dataForm: {
          key: ''
        },
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        showInput: "",
        oldData: {},
        currentData: {},
        supllierTypes:[],
        //导入
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "导入药品数据",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          // updateSupport: 0,
          // 设置上传的请求头部
          // 上传的地址
          url: `${window.SITE_CONFIG.baseUrl}/product/supplier/importData`
        },
        //上传的文件
        excelList: [],
        previewPath:'',
        imgDialogVisible: false
      }
    },
    components: {
      AddOrUpdate
    },
    activated() {
      this.getDataList()
    },
    methods: {
      // 获取数据列表
      async getDataList() {
        this.dataListLoading = true
        const res = await this.$http({
          url: `/product/supplier/page`,
          method: 'get',
          params: this.$http.adornParams({
            'page': this.pageIndex,
            'limit': this.pageSize,
            'dataForm': this.dataForm
          })
        })
        let data = res.data
        if (data && data.code === 0) {
          this.dataList = data.page.list
          this.totalPage = data.page.totalCount
          this.dataList.forEach(item => {
            item.status = item.status == 1 ? true : false
            item.isShare = item.isShare == 1 ? true : false
          })
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      },
      // 每页数
      sizeChangeHandle(val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle(val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle(val) {
        this.dataListSelections = val
      },
      // 新增 / 修改
      addOrUpdateHandle(id) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id)
        })
      },
      // 删除
      deleteHandle(id) {
        var ids = id ? [id] : this.dataListSelections.map(item => {
          return item.supplierId
        })
        this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const res = await this.$http({
            url: `/product/supplier/delete`,
            method: 'delete',
            data: this.$http.adornData(ids, false)
          })
          let data = res.data
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList()
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      },
      resetForm() {
        this.$nextTick(() => {
          this.dataForm = this.$options.data().dataForm
          this.getDataList()
        })
      },
      async saveHandle(row) {
        row.status = row.status ? 1 : 0
        row.isShare = row.isShare ? 1 : 0
        const res = await this.$http({
          url: `/product/supplier/update`,
          method: 'post',
          data: this.$http.adornData(row)
        });
        let data = res.data
        if (data && data.code !== 0) {
          row.status = !row.status;
          row.isShare = !row.isShare;
          return this.$message.error('修改失败!');
        }
        this.$message.success('更新成功！');
        this.getDataList();
      },
      // 当input失去光标后进行的操作
      async blurInput(row, name, value) {
        // 判断数据是否有所改变，如果数据有改变则调用修改接口
        if (this.oldData[name] != value) {
          row[name] = value
          if (value === true) {
            row[name] = 1
          } else if (value === false) {
            row[name] = 0
          }
        }
        this.showInput = ""
        this.currentData = row
      },
      tableDbEdit(row, column, event) {
        this.showInput = column.property + row.supplierId;
        this.oldData[column.property] = row[column.property];
      },
      async exportData() {
        const res = await this.$http({
          url: `/product/supplier/exportData`,
          method: 'get',
          responseType: 'blob',
          params: this.$http.adornParams()
        });
        downLoadFile(res)
      },
      beforeUpload(file) {
        //截取文件后缀名
        const fileName = file.name.substring(file.name.lastIndexOf('.'));
        if (fileName.toLowerCase() != '.xls' && fileName.toLowerCase() != '.xlsx') {
          this.$message.error('文件必须为.xls或xlsx类型');
          this.fileList = [];
          return false;
        };
        //读取文件大小
        var fileSize = file.size;
        if (fileSize > 3249576) {
          this.uploadShowDialog = false;
          this.$message({
            type: 'error',
            showClose: true,
            duration: 3000,
            message: '文件不能大于3M!'
          });
          return false;
        }
      },
      // excel表上传
      handleUploadChange(file, fileList) {
        if (fileList.length > 0) {
          // 这一步，是展示最后一次选择的文件
          this.fileList = [fileList[fileList.length - 1]];
        }
      },
      //导入按钮
      handleImport() {
        this.upload.open = true;
      },
      //导入提交
      async submitFileForm() {
        if (this.excelList.length === 0) {
          this.$message.warning("请选择文件");
          return;
        }
        if (this.excelList.length > 1) {
          this.$message.warning("每次只能提交一个文件");
          return;
        }
        let formData = new FormData();
        this.excelList.forEach((item) => {
          formData.append("file", item.raw);
        });
        let loadingInstance = Loading.service({
          lock: true, //lock的修改符--默认是false
          text: "导入中", //显示在加载图标下方的加载文案
          spinner: "el-icon-loading", //自定义加载图标类名
          background: "rgba(0, 0, 0, 0.7)", //遮罩层颜色
          target: document.querySelector("#futureTransferDialog"), //loadin覆盖的dom元素节点
        });
        const res = await this.$http({
          url: this.upload.url,
          method: 'post',
          data: formData
        })
        let data = res.data
        if (data && data.code === 0) {
          loadingInstance.close();
          this.$message({
            type: "success",
            message: "导入成功!",
          });
          this.getDataList();
        }
        this.excelList = [];
        this.upload.open = false;
        loadingInstance.close();
        this.dataListLoading = false
      },
      //下载导入模板
      downloadImportTemplate() {
        window.location.href = "http://file.asdzy.com/upload/files/film/供应商模板.xlsx"
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.excelList = fileList;
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      onChangeDr(file, fileList) {
        this.excelList = fileList;
      },
      onRemoveDr(file, fileList) {
        this.excelList = fileList;
      },
      cancelFileForm() {
        this.upload.open = false
        this.excelList = [];
      },
      handleImgPreview(url, i) {
        console.log(url)
        this.previewPath = url
        this.imgDialogVisible = true
      },
      handCloseImgDialog(){
        this.previewPath = ''
        this.imgDialogVisible = false
      },
      async getDicts(type) {
        const res = await this.$http({
          url: '/base/basedict/getDict',
          method: 'get',
          params: this.$http.adornParams({
            'code': type
          })
        })
        let data = res.data
        if (data && data.code === 0) {
          if (type === 'SUPPLY_TYPE') {
            this.supllierTypes = data.data
          }
        }
      },
    },

    directives: {
      // 通过自定义指令实现的表单自动获得光标的操作
      focus: {
        inserted: function(el) {
          if (el.tagName.toLocaleLowerCase() == "input") {
            el.focus()
          } else {
            if (el.getElementsByTagName("input")) {
              el.getElementsByTagName("input")[0].focus()
            }
          }
          el.focus()
        }
      },
      focusTextarea: {
        inserted: function(el) {
          if (el.tagName.toLocaleLowerCase() == "textarea") {
            el.focus()
          } else {
            if (el.getElementsByTagName("textarea")) {
              el.getElementsByTagName("textarea")[0].focus()
            }
          }
          el.focus()
        }
      }
    },
  }
</script>
